<template>
  <div class="user_wrap">
    <!-- 导航位置 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 导航位置 -->
    <div class="userlist">
      <!-- 搜索框 -->
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <div class="input_wrap">
            <el-input
              placeholder="请输入内容"
              v-model="http.params.query"
              @keyup.enter.native="searchuser"
            >
              <el-button
                slot="append"
                class="el-icon-search"
                @click="searchuser"
              ></el-button>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-form-item>
          <el-form-item>
          <el-button type="primary" @click="exports"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 搜索框 -->

      <!-- 用户信息 -->
      <el-table :data="tableData" border style="width: 100%" height="450">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="tableData[scope.$index].mg_state"
              @change="putstate(tableData[scope.$index])"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              content="修改"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                size="mini"
                @click="edit(scope.row.id,'ruleForm1')"
              ></el-button>
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="deluser(scope.row)"
              ></el-button>
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                size="mini"
                @click="role(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 用户信息 -->
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="http.params.pagenum"
          :page-sizes="[2, 5, 15, 20]"
          :page-size="http.params.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totals"
        >
        </el-pagination>
      </div>
      <!-- 分页 -->

      <!-- 添加用户的对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose"
      >
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="70px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              type="text"
              v-model="ruleForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="ruleForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              type="text"
              v-model="ruleForm.email"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input
              type="text"
              v-model="ruleForm.mobile"
              autocomplete="off"
            ></el-input>
          </el-form-item>
         
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- 添加用户的对话框 -->

      <!-- 修改用户的对话框 -->
<el-dialog
  title="修改用户信息"
  :visible.sync="dialogVisible1"
  width="40%"
  :before-close="handleClose">
  <span>
     <el-form
          :model="ruleForm1"
          status-icon
          :rules="rules"
          ref="ruleForm1"
          label-width="70px"
          class="demo-ruleForm"
        >

        <el-form-item label="用户名" prop="username">
            <el-input
              type="text"
              v-model="ruleForm1.username"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              type="text"
              v-model="ruleForm1.email"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="mobile">
            <el-input
              type="text"
              v-model="ruleForm1.mobile"
              autocomplete="off"
            ></el-input>
          </el-form-item>
         
        </el-form>
  </span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible1=false">取 消</el-button>
    <el-button type="primary" @click="subedit('ruleForm1')">确 定</el-button>
  </span>
</el-dialog>

      <!-- 修改用户的对话框 -->

      <!-- 修改角色的对话框 -->
        <el-dialog
  title="分配角色"
  :visible.sync="dialogVisible2"
  width="30%"
  :before-close="handleClose">
  <span>
        <el-form
          :model="ruleForm2"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="90px"
          class="demo-ruleForm"
        >
          <el-form-item label="当前用户:" >
           {{ruleForm2.username}}
          </el-form-item>
          <el-form-item label="当前角色:" >
           {{ruleForm2.role_name}}
          </el-form-item>
           <el-form-item label="分配角色:" >
             <el-select v-model="roles" placeholder="请选择管理角色">
      <el-option label="主管" value="1"></el-option>
      <el-option label="权限管理员" value="2"></el-option>
      <el-option label="商品管理员" value="3"></el-option>
      <el-option label="订单管理员" value="4"></el-option>
      <el-option label="数据统计员" value="5"></el-option>
      <el-option label="超级管理员" value="6"></el-option>
    </el-select>
          </el-form-item>
         
        </el-form>
  </span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible2 = false">取 消</el-button>
    <el-button type="primary" @click="subrole">确 定</el-button>
  </span>
</el-dialog>

      <!-- 修改角色的对话框 -->
    </div>
  </div>
</template>
<script>
import minx from '../../minixs/index'
export default {
  name: "user",
  data() {
    return {
       http: {
        method: "get",
        url: "users",
        params:{
          query: "",
        pagenum: 1,
        pagesize: 5,
        }
      },
      type: "users",
      tableData: [
        {
          id: 25,
          username: "tige117",
          mobile: "18616358651",
          type: 1,
          email: "tige112@163.com",
          mg_state: true, //
          role_name: "炒鸡管理员",
        },
      ],
      currentPage4: 4, //当前页码
      totals: 0, //总的数据
      
      username: "", //查询字符，
      dialogVisible: false, //控制对话框的显示和隐藏，
      ruleForm: {//存放添加用户的数据
        username: "",
       password:"",
       email:"",
       mobile:""
      },
      dialogVisible1:false,//修改数据的显示和隐藏
      ruleForm1:{//修改用户的数据存放
          username:"1",
          email:"1",
          mobile:"1"
      },
      // 控制角色分配的按钮
      dialogVisible2:false,
    //角色的数据
      ruleForm2:{},
      // 管理员角色
      roles:"",
    
    //表单数据规则
      rules:{
        username:[
        { required: true, trigger: 'blur', message: "用户名格式错误"},
        
        ],
        password:[
          {required:true,trigger: 'blur', message: "请输入密码"},
       
        ],
        email:[
          {required:true,trigger: 'blur', message: "请输入邮箱号"},
        ],
        mobile:[
          {required:true,trigger: 'blur', message: "请输入手机号"},
        ]
    },
    };
  },
  mixins:[minx],
  created() {
    // 获取数据
    this. getList();
    // this.con()
  },
  methods: {
    //表格导出
    exports(){
      require.ensure([], () => {
          const { export_json_to_excel } = require('../../vendor/Export2Excel');
            const tHeader = ['姓名', '邮箱', '电话', '角色','状态'];//表头
            const filterVal = ['username', 'email', 'mobile', 'role_name','mg_state'];//显示数据
            const list = this.tableData;
            const data = this.formatJson(filterVal, list);
            export_json_to_excel(tHeader, data, '用户列表');
          })

    },
    formatJson(filterVal, jsonData) {
          return jsonData.map(v => filterVal.map(j => v[j]))
        },
    handleSizeChange(val) {
      this.http.params.pagesize = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.http.params.pagenum = val;
      this.getList();
    },
    // 获取用户数据
    async getList() {
      let data = await this.$http.get("users", { params: this.http.params });
      if (data.meta.status !== 200)
        return this.$message.error("获取用户数据失败");
      this.tableData = data.data.users;
      
      this.totals = data.data.total;
      // if (this.tableData.length) {
      //   this.$message.success("获取用户数据成功");
      // } else {
      //   this.$message.warning("匹配不到用户数据");
      // }
    },
    // 修改用户状态
    async putstate(val) {
      let data = await this.$http.put(`users/${val.id}/state/${val.mg_state}`);
      if (data.meta.status !== 200)
        return this.$message.error("用户状态更新失败");
      this.$message.success("用户状态更新成功");
    },
    // 查询用户
    searchuser() {
      this.getList();
      this.http.params.query = "";
    },

    // 添加用户的关闭按钮
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    // 提交表单
    submitForm(formName){
        this.$refs[formName].validate( async valid => {
          if (valid) {
            let data = await this.$http.post('users',this.ruleForm)
            if(data.meta.status !== 201) return this.$message.error("添加失败")
            this.$message.success("用户添加成功")
            this.getList()
            this.dialogVisible = false  
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    // 取消表单提交
 resetForm(formName) {
        this.$refs[formName].resetFields();
        this.dialogVisible=false
      },
  //  根据id删除用户
  deluser(user){
      this.open(user)
      
  },

   async putdel(user){
       let data = await this.$http.delete(`users/${user.id}`)
    if(data.meta.status !==200) return this.$message.error("删除失败")
    this.$message.success("删除用户成功")
    this.getList()
    },

    // 确认框
     open(user) {
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

        this.putdel(user)
         
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      // 修改
    async edit(id,formName){
          
         let data = await this.$http.get(`users/${id}`)
         if(data.meta.status !== 200){
              this.$message.error("获取信息失败")
              return
         }
        this.dialogVisible1 = true
        this.ruleForm1 = data.data
        setTimeout(()=>{
          this.$refs[formName].validate(valid=>{
            if(valid){

            }else{
              return
            }
          })
        })
      },

      // 提交修改
      subedit(formName){
      this.$refs[formName].validate(async valid=>{
      if(valid){
          let {email,id,mobile} =this.ruleForm1
         
         let data =  await this.$http.put(`users/${id}`,{email,mobile})
          console.log(data)
         if(data.meta.status !==200){
            this.$message.error("更新失败")
            return
         }else{
           this.$message.success("更新成功")
           this.getList()
         }
         this.dialogVisible1=false

        }else{
            return
        }
      })

        },

        // 打开分配角色
        role(user){
          this.ruleForm2 = user
          this.roles =  this.ruleForm2.role_name
          this.dialogVisible2 = true
          
        },

        //发起分配角色请求
        subrole(){
          this.putrole()
        },
        putrole(){
            this.$http.put(`users/${this.ruleForm2.id}/role`,{rid:this.filterrole}).then(res=>{
              this.getList()


              console.log(this.filterrole)

                this.dialogVisible2 = false
             

            })
        }



  },
  computed: {
    keywords() {
      return this.tableData.filter(
        (item, index, arr) => item.username == this.username
      );
    },
    filterrole(){
      switch(this.roles){
        case "主管" :
          return 1;
          break;
        case "权限管理员" :
            return 2;
            break;
        case "商品管理员" :
            return 3;
            break;
         case "订单管理员" :
            return 4;
            break;
          case "数据统计员" :
            return 5;
            break; 
          case "超级管理员" :
            return 6;
            break; 
          default :
          return this.roles;
          break;

      }
    }
  },
};
</script>
<style scoped lang="less">
.userlist {
  text-align: left;
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
}
.search_wrap {
  width: 300px;
}
.block {
  margin-top: 20px;
}

</style>